package com.telife.component;

import com.telife.Main;
import com.telife.constant.CommonConstant;
import com.telife.entity.App;
import com.telife.model.AppModel;
import com.telife.pojo.SharedValue;
import com.telife.util.CommonUtil;
import com.telife.util.ViewUtil;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Cursor;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;

import java.io.File;
import java.net.URL;
import java.util.Optional;

/**
 * 添加或者修改App的对话框
 *
 * @author york
 * @since 2020/6/10
 */
public class InsertOrUpdateAppDialog {

    private Dialog<AppModel> dialog;

    private ImageView imageView;

    /**
     * 选择的文件的地址
     */
    private String filePath;

    /**
     * 应用名称文本框
     */
    private TextField appNameTextField;

    /**
     * 应用描述文本域
     */
    private TextArea appDescTextArea;

    /**
     * 应用访问地址文本框
     */
    private TextField appUrlTextField;

    /**
     * 参数校验结果
     */
    private String paramCheckResult;

    /**
     * 确定按钮
     */
    private ButtonType saveButtonType;


    public InsertOrUpdateAppDialog() {
        dialog = new Dialog<AppModel>();
    }

    /**
     * 公用基础模块
     */
    private void base(String title) {
        dialog.setTitle(title);
        dialog.initOwner(Main.getStage());
        //设置按钮类型
        saveButtonType = new ButtonType("保存", ButtonBar.ButtonData.OK_DONE);
        dialog.getDialogPane().getButtonTypes().addAll(saveButtonType, ButtonType.CANCEL);

        //自定义布局和元素
        GridPane gridPane = new GridPane();
        gridPane.setPadding(new Insets(30, 10, 20, 10));
        gridPane.setPrefWidth(600);
        gridPane.setPrefHeight(400);
        gridPane.setAlignment(Pos.CENTER);
        gridPane.setHgap(10);
        gridPane.setVgap(20);

        //图像显示控件
        imageView = new ImageView();
        //设置imageView的游标
        imageView.setCursor(Cursor.HAND);
        imageView.setFitWidth(150);
        imageView.setFitHeight(150);
        URL url = getClass().getClassLoader().getResource("resources/icon/upload.jpg");
        imageView.setImage(new Image(url.toExternalForm()));

        //点击imageView，打开文件选择框，并更换图片（如果有选择文件）
        imageView.setOnMouseClicked(event -> setImage());

        //应用名称控件组
        Label appNameLabel = new Label("应用名称:");
        appNameTextField = new TextField();

        //应用描述控件组
        Label appDescLabel = new Label("应用描述:");
        appDescTextArea = new TextArea();
        //设置文本域自动换行
        appDescTextArea.setWrapText(true);
        appDescTextArea.setPrefWidth(200);
        appDescTextArea.setPrefHeight(100);

        //应用访问地址控件组合
        HBox appUrlGroup = new HBox();
        appUrlGroup.setAlignment(Pos.BASELINE_CENTER);
        Label appUrlLabel = new Label("访问地址:");
        appUrlTextField = new TextField();
        appUrlGroup.getChildren().addAll(appUrlLabel, appUrlTextField);

        //往表格中添加元素
        gridPane.add(imageView, 1, 0);

        gridPane.add(appNameLabel, 0, 1);
        gridPane.add(appNameTextField, 1, 1);

        gridPane.add(appDescLabel, 0, 2);
        gridPane.add(appDescTextArea, 1, 2);

        gridPane.add(appUrlLabel, 0, 3);
        gridPane.add(appUrlTextField, 1, 3);

        //设置自定义对话框的组件内容
        dialog.getDialogPane().setContent(gridPane);

        //监听保存按钮的事件，点击"保存"后，校验参数，如果参数不符合规则，则不关闭对话框
        Button saveButton = (Button) dialog.getDialogPane().lookupButton(saveButtonType);
        saveButton.addEventFilter(ActionEvent.ACTION, event -> {
            boolean isCheckPass = checkParam();
            if (!isCheckPass) {
                new AlertDialog().showAndWait(Alert.AlertType.ERROR, "错误", paramCheckResult);
                event.consume();
            }
        });
        //点击"保存"按钮后，保存新的应用信息
        dialog.setResultConverter(dialogButton -> {
            if (dialogButton == saveButtonType) {
                App app = paramToApp();
                return CommonUtil.appToAppModel(app);
            }
            return null;
        });
    }


    public Optional<AppModel> showAndWait() {
        base("添加应用");
        return dialog.showAndWait();
    }

    public Optional<AppModel> showAndWait(App app) {
        base("编辑应用");
        imageView.setImage(ViewUtil.setImage(app.getImgUrl()));
        filePath = CommonConstant.APP_IMAGE_FILE + app.getImgUrl();
        appNameTextField.setText(app.getAppName());
        appDescTextArea.setText(app.getAppDesc());
        appUrlTextField.setText(app.getAppUrl());
        //重写保存按钮后的方法
        dialog.setResultConverter(dialogButton -> {
            if (dialogButton == saveButtonType) {
                //将旧图片的地址放入共享变量tempImgPath中
                SharedValue.tempImgPaths.add(app.getImgUrl());
                App newApp = paramToApp();
                return CommonUtil.appToAppModel(newApp);
            }
            return null;
        });
        return dialog.showAndWait();
    }

    /**
     * 检测参数
     *
     * @return true代表检验通过
     */
    private boolean checkParam() {
        //应用名是否为空
        boolean nameIsEmpty = appNameTextField.getText().trim().isEmpty();
        //应用描述是否为空
        boolean descIsEmpty = appDescTextArea.getText().trim().isEmpty();
        //应用访问地址是否为空
        boolean appUrlIsEmpty = appUrlTextField.getText().trim().isEmpty();
        //应用图标地址是否为空
        boolean appImgUrlIsEmpty = filePath == null || filePath.isEmpty();

        if (nameIsEmpty) {
            paramCheckResult = "应用名称不能为空";
            return false;
        }
        if (descIsEmpty) {
            paramCheckResult = "应用描述信息不能为空";
            return false;
        }
        if (appUrlIsEmpty) {
            paramCheckResult = "应用访问地址不能为空";
            return false;
        }
        //如果应用访问地址不为空，则检测地址是否合法
        String appUrl = appUrlTextField.getText().trim();
        if (!CommonUtil.matcheUrl(appUrl)) {
            paramCheckResult = "应用访问地址不合法";
            return false;
        }
        if (appImgUrlIsEmpty) {
            paramCheckResult = "请设置应用图标";
            return false;
        }
        return true;
    }

    /**
     * 把参数转换成实体类
     *
     * @return
     */
    public App paramToApp() {
        App app = new App();
        //去除"file:"字符串，否则编辑app应用进行保存时，头像地址会发生错误
        String newFilePath = filePath.replace("file:","");
        File file = new File(newFilePath);
        app.setAppName(appNameTextField.getText().trim());
        app.setAppDesc(appDescTextArea.getText().trim());
        app.setImgUrl(file.toURI().toString());
        app.setAppUrl(appUrlTextField.getText().trim());
        return app;
    }


    /**
     * 获取文件路径并且设置图像
     */
    public void setImage() {
        filePath = new FileChooserDialog().showAndWait();
        if (filePath != null) {
            File file = new File(filePath);
            imageView.setImage(new Image(file.toURI().toString()));
        }
    }



}
